#!/usr/bin/env python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


from ..._main import PamGroup, PamControl, FeatureBase
from ..._error import VerifyError, FeatureNotFoundError
from ..._feature_common import Fc


class Loginuid(FeatureBase):

    SO = "pam_loginuid.so"

    def __init__(self, context, pam_service):
        super().__init__(context, pam_service)

        # FIXME: I am still not very clear what this module does
        raise FeatureNotFoundError()

        if Fc.groupsHasModule(self._pamService._data, (PamGroup.SESSION, False), self.SO):
            raise VerifyError("%s can only be used for group \"%s\"" % (self.SO, PamGroup.SESSION), self._pamService.file_path)

        ruleList, _ = Fc.getPamGroup(self._pamService._data, PamGroup.SESSION, lambda x: x.module_path == self.SO)
        if len(ruleList) == 0:
            raise FeatureNotFoundError()
        if len(ruleList) > 1:
            raise VerifyError("%s used for multiple times" % (self.SO), self._pamService.file_path)
        if ruleList[0].control != PamControl.OPTIONAL:
            raise VerifyError("%s can only be used for control \"%s\"" % (self.SO, PamControl.OPTIONAL), self._pamService.file_path)
        if ruleList[0].module_arguments is not None:
            raise VerifyError("%s should not have any argument" % (self.SO), self._pamService.file_path)

    @staticmethod
    def name():
        return "loginuid"

    def verify_after_init(self):
        pass

    def modify(self, target_data, add_or_remove):
        assert False


class UnixLog(FeatureBase):

    SO = "pam_unix.so"

    def __init__(self, context, pam_service):
        super().__init__(context, pam_service)

        raise FeatureNotFoundError()

        ruleList, _ = Fc.getPamGroup(self._pamService._data, PamGroup.SESSION, lambda x: x.module_path == self.SO)
        if len(ruleList) == 0:
            return None

        if len(ruleList) > 1:
            raise VerifyError("%s used for multiple times" % (self.SO), self._pamService.file_path)
        if ruleList[0].control != PamControl.OPTIONAL:
            raise VerifyError("%s can only be used for control \"%s\"" % (self.SO, PamControl.OPTIONAL), self._pamService.file_path)
        if ruleList[0].module_arguments is not None:
            raise VerifyError("%s should not have any argument" % (self.SO), self._pamService.file_path)

    @staticmethod
    def name():
        return "unix-log"

    def verify_after_init(self):
        pass

    def modify(self, target_data, add_or_remove):
        assert False


class UpdateLastLog(FeatureBase):

    SO = "pam_lastlog.so"

    def __init__(self, context, pam_service):
        super().__init__(context, pam_service)

        # we don't use the lock-out-user function of pam_lastlog.so
        if Fc.groupsHasModule(self._pamService._data, (PamGroup.SESSION, False), self.SO):
            raise VerifyError("%s can only be used for group \"%s\"" % (self.SO, PamGroup.SESSION), self._pamService.file_path)

        ruleList, _ = Fc.getPamGroup(self._pamService._data, PamGroup.SESSION, lambda x: x.module_path == self.SO)
        if len(ruleList) == 0:
            raise FeatureNotFoundError()
        if len(ruleList) > 1:
            raise VerifyError("%s used for multiple times" % (self.SO), self._pamService.file_path)
        if ruleList[0].control != PamControl.OPTIONAL:
            raise VerifyError("%s can only be used for control \"%s\"" % (self.SO, PamControl.OPTIONAL), self._pamService.file_path)

        # only silent argument is allowed
        self._silent = False
        if ruleList[0].module_arguments is not None:
            margList = ruleList[0].module_arguments.split(" ")
            if len(margList) > 1:
                raise VerifyError("invalid arguments for %s" % (self.SO), self._pamService.file_path)
            if margList[0] != "silent":
                raise VerifyError("invalid arguments for %s" % (self.SO), self._pamService.file_path)
            self._silent = True

    @staticmethod
    def name():
        return "update-lastlog"

    def verify_after_init(self):
        pass

    @property
    def silent(self):
        return self._silent

    def modify(self, target_data, add_or_remove):
        assert False


class Motd(FeatureBase):

    SO = "pam_motd.so"

    def __init__(self, context, pam_service):
        super().__init__(context, pam_service)

        if Fc.groupsHasModule(self._pamService._data, (PamGroup.SESSION, False), self.SO):
            raise VerifyError("%s can only be used for group \"%s\"" % (self.SO, PamGroup.SESSION), self._pamService.file_path)

        ruleList, _ = Fc.getPamGroup(self._pamService._data, PamGroup.SESSION, lambda x: x.module_path == self.SO)
        if len(ruleList) == 0:
            raise FeatureNotFoundError()
        if len(ruleList) > 1:
            raise VerifyError("%s used for multiple times" % (self.SO), self._pamService.file_path)
        if ruleList[0].control != PamControl.OPTIONAL:
            raise VerifyError("%s can only be used for control \"%s\"" % (self.SO, PamControl.OPTIONAL), self._pamService.file_path)
        if ruleList[0].module_arguments is not None:
            raise VerifyError("%s should not have any argument" % (self.SO), self._pamService.file_path)

    @staticmethod
    def name():
        return "motd"

    def verify_after_init(self):
        pass

    def modify(self, target_data, add_or_remove):
        assert False


class Limits(FeatureBase):

    SO = "pam_limits.so"

    def __init__(self, context, pam_service):
        super().__init__(context, pam_service)

        if Fc.groupsHasModule(self._pamService._data, (PamGroup.SESSION, False), self.SO):
            raise VerifyError("%s can only be used for group \"%s\"" % (self.SO, PamGroup.SESSION), self._pamService.file_path)

        ruleList, _ = Fc.getPamGroup(self._pamService._data, PamGroup.SESSION, lambda x: x.module_path == self.SO)
        if len(ruleList) == 0:
            raise FeatureNotFoundError()
        if len(ruleList) > 1:
            raise VerifyError("%s used for multiple times" % (self.SO), self._pamService.file_path)
        if ruleList[0].control != PamControl.REQUIRED:
            raise VerifyError("%s can only be used for control \"%s\"" % (self.SO, PamControl.REQUIRED), self._pamService.file_path)

    @staticmethod
    def name():
        return "limits"

    def verify_after_init(self):
        pass

    def modify(self, target_data, add_or_remove):
        if add_or_remove:
            assert False
        else:
            Fc.pamGroupRemoveModule(target_data, "*", self.SO)


class XAuth(FeatureBase):

    SO = "pam_xauth.so"

    def __init__(self, context, pam_service):
        super().__init__(context, pam_service)

        if Fc.groupsHasModule(self._pamService._data, (PamGroup.SESSION, False), self.SO):
            raise VerifyError("%s can only be used for group \"%s\"" % (self.SO, PamGroup.SESSION), self._pamService.file_path)

        ruleList, _ = Fc.getPamGroup(self._pamService._data, PamGroup.SESSION, lambda x: x.module_path == self.SO)
        if len(ruleList) == 0:
            raise FeatureNotFoundError()
        if len(ruleList) > 1:
            raise VerifyError("%s used for multiple times" % (self.SO), self._pamService.file_path)
        if ruleList[0].control != PamControl.OPTIONAL:
            raise VerifyError("%s can only be used for control \"%s\"" % (self.SO, PamControl.OPTIONAL), self._pamService.file_path)

    @staticmethod
    def name():
        return "xauth"

    def verify_after_init(self):
        pass

    def modify(self, target_data, add_or_remove):
        if add_or_remove:
            assert False
        else:
            Fc.pamGroupRemoveModule(target_data, "*", self.SO)


__all__ = [
    "Loginuid",
    "UnixLog",
    "UpdateLastLog",
    "Motd",
    "Limits",
    "XAuth",
]
